package com.uu.safeguard.utils;

import com.squareup.okhttp.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {

    public static String get(String url, HashMap<String, String> header) {
        String result = "";

        OkHttpClient client = new OkHttpClient();


        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url);

        if(header.size() > 0){
            for(Map.Entry<String, String> entry : header.entrySet()){
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        requestBuilder.addHeader("Content-Type", "text/plain; charset=utf-8");
        requestBuilder.addHeader("cache-control", "no-cache");

        requestBuilder.get();
        Request request = requestBuilder.build();


        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }

    public static String post(String url, HashMap<String, String> header, String content) {

        String result = "";

        OkHttpClient client = new OkHttpClient();

        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url);

        if(header.size() > 0){
            for(Map.Entry<String, String> entry : header.entrySet()){
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        requestBuilder.addHeader("cache-control", "no-cache");
        requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8");

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        requestBuilder.post(body);
        Request request = requestBuilder.build();

        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }


}
